define(['jquery'],function($){
    $.extend({
        len:function(str,type){
			if(type==1){
				var num=Math.ceil(str.replace(/[^\x00-\xff]/g,"aa").length/2)
			}else{
				var num=str.length;
			}
            return num;
        },
        closeTip : function(a) {
            if(a){
                $(".tips-stic",a).remove();
            }else{
                $(".tips-stic").remove();
            }            
        },
		unique:function(arr){ //数组除重
			var result = [], hash = {};
			for (var i = 0, elem; (elem = arr[i]) != null; i++) {
				if (!hash[elem]) {
					result.push(elem);
					hash[elem] = true;
				}
			}
			return result;
		}
    });

    $.fn.extend({
        tab: function(t, m) {
            var tabt = $(this).find(t);
            var tabc = $(this).find(m);

            tabt.click(function() {
                $(this).addClass('active').siblings().removeClass('active');
                tabc.eq($(this).index()).show().siblings().hide();
            });
            tabt.eq(0).click();
        },
	    checkAll:function(o){
            return this.each(function(){
                var t=$(this);
                t.change(function(){
                    if(t.is(':checked')){
                        $(o).prop('checked',true);
                    }else{
                        $(o).prop('checked',false);
                    }
                });

            });
        },checkAll:function(o,fn){
            return this.each(function(){
                var t=$(this);
                t.change(function(){
                    if(t.is(':checked')){
                        $(o).prop('checked',true);
                    }else{
                        $(o).prop('checked',false);
                    }
                    if($.isFunction(fn)) fn();
                });

            });
        },
        timeout:function(name,time,classs){
            return this.each(function() {
                var t = $(this);
                var i = time;
                var timer = null;

                function a() {
                    timer = setTimeout(function () {
                        i--;
                        t.val(name+'('+i+')');
                        if (i <= 0) {
                            t.val(name).removeClass(classs);
                            clearTimeout(timer);
                        }else{
                            a();
                        }
                    }, 1000);
                }

                a();
            });
        },
		tipbox:function(a,timeout){
            return this.each(function(){
                var _this=$(this);
                
                if(typeof(a) =='string'){
                    a={title:a};
                }
                var defaults={
                    align:'top',
                    hover:0    //鼠标可经过提示框
                };
                var s = $.extend({},defaults,a);
                $.closeTip(s.iframe);
                
                var f,timer=null;
                var bom='<span class="tips-stic"><span class="arrow_b1"></span>'+s.title+'</span>';
                if(s.iframe){
                    $("body",s.iframe).append(bom);
                    f = $(".tips-stic",s.iframe);
                }else{
                    $("body").append(bom);
                    f = $(".tips-stic");
                }
                if(s.icon){
                    var icon='';
                    switch(s.icon){
                        case 'error':
                            icon='er';
                            break;
                        case 'success':
                            icon='cr';
                            break;
                    }
                    f.find('span').after('<i class="icon-'+icon+'"></i>');
                }
                
                if(s.zindex){
                    f.css({'z-index': s.zindex});
                }
                f.show();        
                if(s.hover==1){
                    clearTimeout(timer);                    
                    _this.unbind('mouseleave').bind('mouseleave',function() {
                        clearTimeout(timer);
                        timer = setTimeout(function() { $.closeTip(s.iframe); },timeout);
                    });
                    f.unbind('mouseenter').bind('mouseenter',function() {
                        clearTimeout(timer);
                    });
                    f.unbind('mouseleave').bind('mouseleave',function() {
                        clearTimeout(timer);
                        timer = setTimeout(function() { $.closeTip(s.iframe); },timeout);
                    });
                }else{
                    if(timeout){
                        timer=setTimeout(function(){ $.closeTip(s.iframe); },timeout);
                    }
                }
				
				var ol=_this.offset().left;
                var ot=_this.offset().top;
                var ow=_this.outerWidth();
                var oh=_this.outerHeight();
                var fw=f.outerWidth();
                var fh=f.outerHeight();
				
                switch(s.align){
                    case 'top':
                        var j=fw>ow?-(fw-ow)/2:(ow-fw)/2;
                        if(fw>ow && $(window).width()<ol+Math.abs(j)+ow){
                            var l=ol+Math.abs(j)+ow-$(window).width()+2;
                            f.find('.arrow_b1').css({left:fw/2-6+l});
                            f.show().css({display:'inline',left:ol+j-l,top:ot - fh - 12,opacity:"0"});
                            f.animate({left:ol+j-l,top:ot - fh - 7,opacity: "1"},200);
                        }else{
                            f.find('.arrow_b1').css({left:fw/2-6});
                            f.show().css({display:'inline',left:ol+j,top:ot - fh - 12,opacity:"0"});
                            f.animate({left:ol+j,top:ot - fh - 7,opacity: "1"},200);
                        }
                        break;
                    case 'right':
                        
                        break;
                    case 'bottom':

                        break;
                    case 'left':
                        
                        break;
                }
            });
        },replybox:function(o){
            return this.each(function(){
                var t=$(this);
                var bat=null;
                var title="快速回复";
                var replyto='';

                t.on('click',function(){
                    if(t.data('rel')=='bat'){
                        var receive_arr = [],nickname_arr = [], msgid_arr = [];
                        $('[name=item]').each(function(i,obj){
                            if($(obj).attr('checked')){
                                receive_arr.push($(obj).val());
                                var nickname = $(obj).parent('.msgitem').find('.nickname').html();
                                nickname_arr.push('<a href="javascript:void(0)" data-id="'+$(obj).val()+'">'+nickname+'×</a>');
                                msgid_arr.push($(obj).closest('tr').data('id'));
                            }
                        });

                        if(receive_arr.length<1){
                            $(this).tipbox({title:'请选择要回复的消息！',icon:'error'},2000);
                            return false;
                        }

                        receive_arr = $.unique(receive_arr);
                        nickname_arr = $.unique(nickname_arr);

                        var replayto_str = nickname_arr.join('、');

                        bat=1;
                        title="批量回复";
                        replyto='（群发对象：'+replayto_str+'）';

                    }

                    var mhtml=$('<div class="comment-box">'
                        +'<div class="hd"><span class="tt blue">'+title+'：</span><span class="replyto gray9">'+replyto+'</span></div>'
                        +'<textarea class="r-txt com-content"></textarea>'
                        +'<div class="f-detail">'
                        +'    <div class="morecnt">'
                        +'        <a href="javascript:;" class="emot"><i class="icon-emot"></i>表情</a>'
                        +'    </div>'
                        +'    <a href="javascript:;" title="收起" id="close" class="fr btn btn-default"> 收起 </a>'
                        +'    <a href="javascript:;" title="发送" id="submitReply" class="fr btn btn-primary"> 发送 </a>'

                        +'	  <span class="warn fr f14 mt3 tnum">还可以输入<i>140</i>字</span>'
                        +'</div>'
                        +'</div>');

                    //取消回复对象
                    $(mhtml).find('.replyto a').on('click',function(){
                        var opid = $(this).data('id'); alert(opid);
                        $('input[value='+opid+']').attr('checked',false);
                        $(this).remove();
                        $('#selectAll').attr('checked',false);
                    });

                    mhtml.find('.com-content').val('');
                    $('.table').find('.replybox').remove();
                    if(!bat){
                        $(".comment").html('');
                        var rbox=$('<tr class="replybox"><td colspan="100"></td></tr>');
                        t.closest('tr').after(rbox);
                        $(rbox).find('td').html(mhtml);
                    }else{
                        $(".comment").html(mhtml);
                    }

                    $(mhtml).find('#close').on('click',function(){
                        $(mhtml).slideUp(function(){
                            $('.table').find('.replybox').remove();
                            $(".comment").html('');
                        });
                    });
                    $(mhtml).find('#submitReply').on('click',function(){
                        var content=mhtml.find('.com-content');
                        if(content.val()==''){
                            $(this).tipbox({title:'回复内容不能为空！',icon:'error'},2000);
                            return false;
                        }
                        if(content.data('num')<0){
                            $(this).tipbox({title:'回复内容已超过'+Math.abs(content.data('num'))+'个字！',icon:'error'},2000);
                            return false;
                        }

                        if(t.data('rel')=='bat'){
                            //批量回复
                            var receive = receive_arr.join(',');
                            var msgid = msgid_arr.join(',');
                        }else{
                            //单个回复
                            var receive = $(mhtml).closest('tr').prev('tr').find('[name=item]').val();
                            var msgid = $(mhtml).closest('tr').prev('tr').data('id');
                        }

                        var content = content.val();
                        $.post(URL+'/reply',{type:1,receive:receive,content:content,msgid:msgid},function(data){
                            if(data.status==1){
                                mhtml.remove();
                                $('.msgitem .con').showemot();
                                showModelBox(data.info);
                                setTimeout(function(){document.location.reload();},1500);
                            }else{
                                $('#submitReply').tipbox({title:data.info,icon:'error'},2000);
                            }
                        },'json');

                    });

                    mhtml.show();
                    mhtml.comment();
                    $(window).resize();
                });


            });
        },
        comment:function(opts){
            var defaults={
                num:140
            };
            var that = $.extend({},defaults,opts);
            return this.each(function(){
                var t=$(this);
                var textarea=t.find('.com-content');
                var tnum=t.find('.tnum');
                t.find('.emot').emotion(textarea);
                //最多可输入字数
                textarea.maxword({num:that.num,tip:tnum});
            });
        },
		maxword:function(a){
            //
            //num:最多可输入字数
            //tip:返回可输入字体提示
            //
            return this.each(function(){
                var t=$(this);
                var num=a.num?a.num:0;
                var placeholder=a.placeholder?a.placeholder:'';
                var tnum=0;
                if(this.tagName == 'INPUT' || this.tagName == 'TEXTAREA'){
                    var v=t.val();
                    if(v.indexOf(placeholder)>=0){
                        v=v.replace(placeholder,"");
                    }
                    tnum=num-$.len(v);
                    chknum($.len(v));
                    t.on('keyup paste change',function(){
                        v=$(this).val();
                          
                        if($.len(v)>num){
                              
                        }
                          
                        if(v.indexOf(placeholder)>=0){
                            v=v.replace(placeholder,"");                           
                        }
                        tnum=num-$.len(v);
                        chknum($.len(v));
                    });                                        
                }
                function chknum(n){
                    t.data('num',n);
                    if(n>num){
                        $(a.tip).addClass('orange').html('（<i>'+ parseInt(n) +'</i>' + '/'+num+'字）');
                    }else{
                        $(a.tip).removeClass('orange').html('（<i>'+ n +'</i>' + '/'+num+'字）');
                        }
                    if ($.isFunction(a.callback)) a.callback(n);
                }
            });
        },        
        /*图片无变形压缩
        *$('selecter').reSizeImage(80,80);
        */
        reSizeImage:function(reWidth, reHeight,s,c) {
            return this.each(function(){
                var ImgObj=this;
                var image = new Image();
                image.src = ImgObj.src;
                var parent = $(ImgObj).parent();
                var pw = parent.width();
                var ph = parent.height();
                var imgt = 0;
                var imgwc = 0;
                if(!reWidth && !reHeight){
                    reWidth = pw;
                    reHeight = ph;
                }

                if (image.width > 0 && image.height > 0) {
                    if (image.width / image.height >= reWidth / reHeight) {
                        if (image.width > reWidth) {
                            var imgw = reWidth;
                            var imgh = (image.height * reWidth) / image.width;
                        } else {
                            var imgw = image.width;
                            var imgh = image.height;
                        }
                    } else {
                        if (image.height > reHeight) {
                            var imgw = (image.width * reHeight) / image.height;
                            var imgh = reHeight;
                        } else {
                            var imgw = image.width;
                            var imgh = image.height;
                        }
                    }
                    if (imgh < ph && s!=1) {
                        imgt = (ph - imgh) / 2;
                        $(ImgObj).css({'margin-top':imgt});
                    }

                    if(imgwc < pw && c==1){
                        imgwc = (pw - imgw) / 2;
                        $(ImgObj).css({'margin-left':imgwc});
                    }

                    $(ImgObj).css({'width':imgw, 'height':imgh});
                }
            });
        }
    });
});